from rest_framework.mixins import ListModelMixin, CreateModelMixin, RetrieveModelMixin, DestroyModelMixin, \
    UpdateModelMixin
from .common_logger import logger
from utils.common_response import APIResponse
from django.core.cache import cache


class APIListModelMixin(ListModelMixin):
    cache_key = None

    def list(self, request, *args, **kwargs):
        if self.paginator:
            data_list = super().list(request, *args, **kwargs).data
            return APIResponse(
                count=data_list.get('count'),
                next=data_list.get('next'),
                previous=data_list.get('previous'),
                results=data_list.get('results'),
            )
        else:
            assert self.cache_key, '必须设置cache_key'
            data_list = cache.get(self.cache_key)
            if not data_list:
                logger.info('走数据库')
                data_list = super().list(request, *args, **kwargs).data
                cache.set(self.cache_key, data_list)
        return APIResponse(results=data_list)


class APICreateModelMixin(CreateModelMixin):
    def create(self, request, *args, **kwargs):
        res = super().create(request, *args, **kwargs)
        return APIResponse(data=res.data)


class APIRetrieveModelMixin(RetrieveModelMixin):
    def retrieve(self, request, *args, **kwargs):
        res = super().retrieve(request, *args, **kwargs)
        return APIResponse(result=res.data)


class APIDestroyModelMixin(DestroyModelMixin):
    def destroy(self, request, *args, **kwargs):
        res = super().destroy(request, *args, **kwargs)
        return APIResponse(data=res.data)


class APIUpdateModelMixin(UpdateModelMixin):
    def update(self, request, *args, **kwargs):
        res = super().update(request, *args, **kwargs)
        return APIResponse(data=res.data)
